<?php
/**
 * AJAX Handler for Project: Check - Return an ajax call that lists the projects
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    require_once('../../SiteIncludes.GLOBAL.php');
    
    $return_head = <<<EOHEAD
	<!DOCTYPE html>
	    <html>
	    <head><title></title></head>
	    <body>
		<script type="text/javascript">
EOHEAD;
    $return_nok = 'parent.EDJXConfirmer.show_nok(); ';
    $return_ok = 'parent.EDJXConfirmer.show_ok(); ';
    $return_body = '';
    $return_foot = <<<EOFOOT
		</script>
	    </body>
	</html>
EOFOOT;
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	$gVAR['e'] = '404';
	require_once('error_handler.php');
    }
    
    if(isset($pVAR['search_project_name']) === true) {
	$announcements_title = "Search Results";
	$announcements_url = "";
	$announcements_feed_items = array();
	$search_terms = explode(' ', $pVAR['search_project_name']);
	$safe_name = '';
	$i = 0;
	foreach ($search_terms as $key => $value) {
	    if($i > 0) {
		$safe_name .= ", ";
	    }
	    // PACIFY!
	    $safe_name .= "'".$sql_conx->real_escape_string($value)."'";
	    $i++;
	}
	$query = $sql_conx->query("SELECT DISTINCT `tid` FROM `user_tags` WHERE `tag` IN ({$safe_name}) LIMIT 15;");
	if($query !== false && $query->num_rows > 0) {
	    $i = 0;
	    $tags = "";
	    while($row = $query->fetch_row()) {
		if($i > 0) {
		    $tags .= ", ";
		}
		$tags .= "'".$sql_conx->real_escape_string($row[0])."'";
		$i++;
	    }
	} else {
	    $tags = "SELECT DISTINCT `tid` FROM `user_tags` WHERE `tag` IN ('')";
	}
		/**
		 * I'm sorry that this SQL is so complicated, but it has to search the name of the project, the alias of the project and any associated tags.
		 * To make you feel better, I hope this duck cheers you up:
		 *         ..---.. 
		 *	.'  _    `. 
		 *   __..'  (o)    :	Quack
		 *   `..__          ; 
		 *	`.       / 
		 *	;      `..---...___ 
		 *	.'                   `~-. .-') 
		 *	.                         ' _.' 
		 *  :                           : 
		 *  \                           ' 
		 *	+                         J 
		 *	`._                   _.' 
		 *	    `~--....___...---~' mh 
		 * 
		 * The call above the duck "SELECT DISTINCT FROM `tid`" Gets any tag id's which are associated with the input string.
		 * The subquery "IN (SELECT `pid` FROM `tool_tags` WHERE `tid` IN ({$tags}))" then looks for any projects with these tags
		 * The last three parts inside the brackets: "(`name` LIKE '{$safe_name}' OR `alias` LIKE '{$safe_name}' OR `pid` IN (SELECT `pid` FROM `tool_tags` WHERE `tid` IN ({$tags})))"
		 *	are searching for a match in any of the three (alias, name or tags).
		 * As well as this "WHERE `visible`='1'". The project must be visible.
		 * 
		 * I hope this helps!
		 */
	// PACIFY
	$safe_name = '%'.$sql_conx->real_escape_string(str_replace(' ', '%', $pVAR['search_project_name'])).'%';
	$query = $sql_conx->query("SELECT DISTINCT `pid` FROM `tool_project` WHERE `visible`='1' AND (`name` LIKE '{$safe_name}' OR `alias` LIKE '{$safe_name}' OR `pid` IN (SELECT `pid` FROM `tool_tags` WHERE `tid` IN ({$tags}))) LIMIT 10;");
	if($query !== false && $query->num_rows > 0) {
	    while($row = $query->fetch_assoc()) {
		$item =& $ProjectStash->stash((int)$row['pid']);
		$date = date("d/m/Y", $item->getCreationTime());
		$title = $item->getName();
		$url = EclipseMDE::aliasLink($item->getAlias());
		$description = $item->getDescription();
		$icon = $item->getIconURL();
		$announcements_feed_items[] = $Templater->makecontentfeeditem($date, $title, $url, $description, $icon);
            }
            $callback_unescaped = ($Templater->maincontent_feed($announcements_title, $announcements_url, $announcements_feed_items, ''));
            if(isset($pVAR['adm_srch']) === true && isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && $_LOGGEDINUSER->get_priv_adm() === true) {
                $pattern = '/\<a class=\"btn\" href=\"\/tool\/(.*?)\">View &raquo;\<\/a\>/i';
                $replacement = "<a class=\"btn\" href=\"/tool/$1\">View &raquo;</a> <a class=\"btn\" href=\"/admin/project/$1\">Edit &raquo;</a>";
                $callback_unescaped = preg_replace($pattern, $replacement, $callback_unescaped);
            }
            $callback_unescaped .= <<<EOMORE
                <div class="row-fluid">
                    <div class="span12" style="text-align: center; font-weight: bold; font-style: italic;">Not Here?<br />Try narrowing your search.</div>
                </div>
EOMORE;
	} else {
	    $callback_unescaped = <<<EOERROR
		<div class="row-fluid">
		    <div class="span12" style="text-align: center; font-weight: bold; font-style: italic;">Sorry<br/>No Search results found.</div>
		</div>
EOERROR;
	}
	$callback_escaped = json_encode($callback_unescaped);
	$return_body = $return_ok.' parent.ProjectSearchBox.callback('.$callback_escaped.');';
    } else {
	$return_body = $return_nok.' parent.ProjectSearchBox.callback(\'\');';
    }
    
    echo $return_head.$return_body.$return_foot;
    
?>
